import axios from 'axios'
import {getToken} from './tokenUtil';
import iView ,{Message}from 'iview';
import store from '@/store';
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: "http://localhost:9093/blog/",
  // 超时
  timeout: 10000
});

// request拦截器
service.interceptors.request.use(
  config => {
    //添加token,
    config.headers['Authorization'] = window.localStorage.getItem("token"); // 让每个请求携带自定义token 请根据实际情况自行修改
    //获取token
    return config
  },
  error => {
    console.log(error);
    Promise.reject(error)
  }
);


//响应拦截,非成功,消息提醒
service.interceptors.response.use(res => {
    const code = res.data.code;
    if(code == 401 || code == 403){
      //未登录,重定向到登录页面,清除token
      localStorage.removeItem("token");
      window.location.href = "/login";
    }else if (code !== 200) {
       Message.error(res.data.msg);
    }
    return res;
  },
  error => {
    console.log('err' + error);
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error)
  }
);


export default service
